package br.unirio.webdisco.dao.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PostgresConnection {
	
private String url = "jdbc:postgresql://localhost:5432/DesenWeb";
	
	private String user = "postgres";
	
	private String password = "gabahey";
	
	private String postgresqlDriver = "org.postgresql.Driver";
	
	private Connection connection;
	
	protected Connection criaConexao(Boolean autocommit) throws Exception {
		try {
			Class.forName(postgresqlDriver);
		} catch (ClassNotFoundException e) {
			throw e;
		}
		try {
			connection = DriverManager.getConnection(url, user, password);
			connection.setAutoCommit(autocommit);
		} catch (SQLException e) {
			throw e;
		}
		
		return connection;
	}
	
	protected void fechaConexao() throws SQLException {
		try {
			connection.close();
		} catch (SQLException e) {
			throw e;
		}
	}

	@SuppressWarnings("unused")
	protected Integer recuperaSequence(String nomeSequence) throws Exception {

		this.criaConexao(false);
		String sql = "select nextval('"+ nomeSequence +"') as id";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Integer identificador = null;

		try {
			stmt = connection.prepareStatement(sql);
			rs = stmt.executeQuery();
			if (rs.next()) {
				identificador = rs.getInt("id");
			}

		} catch (SQLException e) {
			throw e;

		} finally {
			try {
				stmt.close();
				rs.close();
				this.fechaConexao();

			} catch (SQLException e) {
				throw e;
			}

		}
		return identificador;
	}
	
}
